package com.coollang.smartbra.manager;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.coollang.smartbra.utils.UIUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by Administrator on 2016/10/21 0021.
 */

public class MapManager implements AMapLocationListener {
    private static final String TAG = "MapManager";
    private static MapManager instance;// 创建单例

    //*******************************定位******************************//
    private AMapLocationClient mLocationClient = null; //声明AMapLocationClient类对象，定位发起端
    public AMapLocationClientOption mLocationOption = null; //声明mLocationOption对象，定位参数

    //******************************跑步**************************//
    private boolean continueRun = false;//继续跑步
    public double distance = 0; //跑步的距离
    public long timer = 0; // 跑步的时间
    public long startTimer = 0;// 开始时间
    public Thread thread; // 控制时间的子线程
    public boolean isRunning = true; // 是否正在运行，正在跑步
    private TimeListener mTimeListener;// 设置时间的监听器
    public long tempTime = 0;//记录暂停前用时
    public HashMap<Integer, List<LatLng>> runPointMap; //跑步所有坐标点；

    private MapManager() {
    }

    public static MapManager getInstance() {
        if (instance == null) {
            instance = new MapManager();
        }
        return instance;
    }

    //**************************************定时****************************************//
    public Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            // 在UI中设置时间
            if (mTimeListener != null) {
                mTimeListener.onTimeChange();
            }
        }
    };

    public interface TimeListener {
        public void onTimeChange();
    }

    public void setTimeListener(TimeListener mTimeListener) {
        this.mTimeListener = mTimeListener;
    }

    /**
     * 初始化时间
     */
    public void initTime() {
        runPointMap = new HashMap<>();
/*        if (thread == null) {
            runPointMap = new HashMap<>();
            startTimer = System.currentTimeMillis();
            thread = new Thread() {
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (isRunning) {
                            if (startTimer != System.currentTimeMillis()) {
                                timer = tempTime + System.currentTimeMillis() - startTimer;
                            }
                            Message msg = new Message();
                            handler.sendMessage(msg);// 通知主线程
                        }
                    }
                }
            };
            thread.start();
        }
        if (mTimeListener != null) {
            mTimeListener.onTimeChange();
        }*/
    }

    /**
     * 点击完成跑步，时间停止
     */
    public void timeFinish() {
        isRunning = false;
        handler.removeCallbacks(thread);
    }

    /**
     * 点击继续跑步，时间继续增加
     */
    public void timeContinue() {
        isRunning = true;
        startTimer = System.currentTimeMillis();
        tempTime = timer;
        if (mTimeListener != null) {
            mTimeListener.onTimeChange();
        }
    }

    //**************************************定位相关*************************************//
    // 设置定位的监听器
    private LocationSucceedListener locationListener;

    public void setLocationListener(LocationSucceedListener locationListener) {
        this.locationListener = locationListener;
    }

    public interface LocationSucceedListener {
        public void onLocation(AMapLocation aMapLocation);
    }

    public void initMap() {
        // 定位初始化
        if (mLocationClient == null) {
            //初始化定位
            mLocationClient = new AMapLocationClient(UIUtils.getContext());
            //设置定位回调监听
            mLocationClient.setLocationListener(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否只定位一次,默认为false
            mLocationOption.setOnceLocation(false);
            //设置是否强制刷新WIFI，默认为强制刷新
            mLocationOption.setWifiActiveScan(true);
            //设置是否允许模拟位置,默认为false，不允许模拟位置
            mLocationOption.setMockEnable(false);
            //设置定位间隔,单位毫秒,默认为2000ms
            mLocationOption.setInterval(2000);
            //给定位客户端对象设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            //启动定位
            mLocationClient.startLocation();
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                if (locationListener != null && aMapLocation != null) {
                    locationListener.onLocation(aMapLocation);
                }
//                getDistance(MapUtil.getLocationLatLng(aMapLocation));
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:" + aMapLocation.getErrorCode() + ", errInfo:" + aMapLocation.getErrorInfo());
//                Toast.makeText(UIUtils.getContext(), "定位失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    public void getDistance(LatLng locationLatLng, long length) {
//        int t = (int) (timer / 1000);
        // 继续刷街
        if (continueRun) {
            if (runPointMap.size() > 0) {
                List<LatLng> prePointList = runPointMap.get(runPointMap.size() - 1);
                if (prePointList.size() > 0) {
                    LatLng lastPoint = prePointList.get(prePointList.size() - 1);
                    List<LatLng> stopPointList = new ArrayList<>();
                    stopPointList.add(lastPoint);
                    stopPointList.add(locationLatLng);
                    runPointMap.put(runPointMap.size(), stopPointList);
                }
                runPointMap.put(runPointMap.size(), new ArrayList<LatLng>());
            }
            continueRun = false;
        }
        if (runPointMap != null && length > 6) {
            if (runPointMap.isEmpty()) {
                runPointMap.put(0, new ArrayList<LatLng>());
            }
            toCalculateDistance(locationLatLng);
        }
    }

    /**
     * 计算记步距离
     *
     * @param ll
     */
    private void toCalculateDistance(LatLng ll) {
        List<LatLng> curPointList = runPointMap.get(runPointMap.size() - 1);//当前定位点的前一个定位点
        curPointList.add(ll);//添加当前定位点,以计算距离
        if (curPointList.size() >= 2) {
            double d = AMapUtils.calculateLineDistance(curPointList.get(curPointList.size() - 1), curPointList.get(curPointList.size() - 2));
//                //100m内的偏差去掉
            if (d < 100) {
                distance += d;
            } else {
                curPointList.remove(curPointList.size() - 1);
            }
        }
        runPointMap.put(runPointMap.size() - 1, curPointList);
    }

    /**
     * 停止定位，并释放资源
     */
    public void stopLocClient() {
        instance = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();//停止定位
            mLocationClient.onDestroy();//销毁定位客户端。
        }
        mLocationClient = null;
//        mTimeListener = null;
        locationListener = null;
    }

    public void pauseLocClient() {
        mLocationClient.stopLocation();
    }

    public void restartLocClient() {
        continueRun = true;
        mLocationClient.startLocation();
    }
}
